import { done, initExecute } from './index.js';
class RenderGroup {
	constructor(buildItem, config = {}, info) {
		const { area, hook } = buildItem;
		// 普通下拉和下拉组，都共用$options
		const { $options, children, ...param } = info;
		this.area = area;
		this.hook = hook;
		this.param = param;
		this.config = config;
		// 开始执行渲染
		this[config.method](children || $options);
		return this.param;
	}
	initOptions(options) {
		const { area, param, config } = this;
		// 处理得到当前可以使用的子项数据
		options = done(options, (data) => {
			// 通过回调或响应式，获取新的子项数据，根据此数据立即更新组件
			let childs = null;
			// 重新获取渲染对象，该过程会自动存入缓存
			if (config.method === 'selectGroup') {
				// 分组下拉
				childs = this.getGroups(data);
			} else {
				childs = this.getOptions(data);
			}
			// 更新子项集合
			area.param.childsProxy[param.name] = childs;
		});
		return options;
	}
	getOptions(options, groupKey = 'no-group_') {
		const { area, hook, config } = this;
		const { is, method } = config;
		const { ctx, exec } = area;
		// 此刻的options还可能有多种数据类型
		options = this.initOptions(options);
		if (Array.isArray(options)) {
			return options.map((option, key) => {
				let { value, text, render, ...attrs } = option;
				// 自定义渲染每一个子项的内容
				text = exec(render, [option], text);
				// 下拉框中的下拉项通过此条件
				if (method.includes('select')) {
					// 这里依然根据原框架环境判断
					key = groupKey + key + '_option';
					const param = { is, value, children: text, ...attrs };
					const args = [cb => cb(param), text, key];
					text = hook.hookGetOptionsSelect(...args);
					return param;
				} else {
					const param = { is, key, children: text, ...attrs };
					param[hook.optionsValueField] = value;
					return param;
				}
			});
		} else {
			return [];
		}
	}
	getGroups(groups) {
		// 此刻的groups还可能有多种数据类型
		return this.initOptions(groups)
			// 获取分组下拉的初始渲染数据
			.map((group, key) => {
				key += '_group_';
				let { text, children, ...o } = group;
				return {
					key,
					label: text,
					is: this.config.Group,
					children:this.getOptions(children, key),
					...o
				};
			});
	}
	// ===========================================================
	radio(options) {
		this.param.children = this.getOptions(options);
	}
	radioButton(options) {
		// 带button的单选框
		this.hook.hookRadioButton(this.param);
		this.param.children = this.getOptions(options);
	}
	checkbox(options) {
		this.param.children = this.getOptions(options);
	}
	checkboxButton(options) {
		// react-antd中没有CheckboxButton
		this.param.children = this.getOptions(options);
	}
	// ===========================================================
	select(options) {
		this.param.children = this.getOptions(options);
	}
	selectGroup(groups) {
		this.param.children = this.getGroups(groups);
	}
}

export default RenderGroup;